package com.freight.base.serviceimpl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.freight.base.dao.ProvinceDao;
import com.freight.base.entity.Province;
import com.freight.base.service.ProvinceService;
import com.freight.core.common.vo.SearchVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 省份维表接口实现
 * @author huyingtai
 */
@Slf4j
@Service
@Transactional
public class ProvinceServiceImpl implements ProvinceService {

    @Autowired
    private ProvinceDao provinceDao;

    @Override
    public ProvinceDao getRepository() {
        return provinceDao;
    }

    @Override
    public Page<Province> findByCondition(Province province, SearchVo searchVo, Pageable pageable) {


        return provinceDao.findAll(new Specification<Province>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<Province> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {

                // TODO 可添加你的其他搜索过滤条件 默认已有创建时间过滤
                Path<Date> createTimeField = root.get("createTime");
                // TODO 可添加你的其他搜索过滤条件 默认已有创建时间过滤
                Path<String> provinceCode = root.get("provinceCode");
                // TODO 可添加你的其他搜索过滤条件 默认已有创建时间过滤
                Path<String> provinceName = root.get("provinceName");

                List<Predicate> list = new ArrayList<>();

                // 创建时间
                if(StrUtil.isNotBlank(searchVo.getStartDate())&&StrUtil.isNotBlank(searchVo.getEndDate())){
                    Date start = DateUtil.parse(searchVo.getStartDate());
                    Date end = DateUtil.parse(searchVo.getEndDate());
                    list.add(cb.between(createTimeField, start, DateUtil.endOfDay(end)));
                }
                // 模糊搜素
                if (StrUtil.isNotBlank(province.getProvinceCode())) {
                    list.add(cb.like(provinceCode, '%' + province.getProvinceCode() + '%'));
                }

                // 模糊搜素
                if (StrUtil.isNotBlank(province.getProvinceName())) {
                    list.add(cb.like(provinceName, '%' + province.getProvinceName() + '%'));
                }
                Predicate[] arr = new Predicate[list.size()];
                cq.where(list.toArray(arr));
                return null;
            }
        }, pageable);
    }

}